$(function() {
	var i = 0;
	fetch('./list.do?type=json&page=0',{credentials: 'same-origin'})
	.then(function(response) {
		return response.json();
	}).then(
			function(articles) {
				var $ul = $('#list-articles');
				articles.forEach(function(art) {
					$ul.append('<li class="list-group-item">' + '<h3>'
							+ art.title + '</h3>' + '<p>' + art.content
							+ '</p>' + '<button class="del-btn" data-id="'
							+ art.id + '">删除</button>' + '</li>');
				})
			}).then(function() {
		$('ul .del-btn').on('click', function() {
			var $self = $(this);
			var id = $self.data('id');
			console.log($self.data('id'));
			fetch('./del.do?ajax=true&id=' + id).then(function(response) {
				return response.json();
			}).then(function(res) {
				if (res.ok === 1) {
					$self.parent().slideUp("slow");
				}
			})
			.catch(function(err){
				alert(err)
			})
		})
	})
	
	function doGet(number){
		var url;
		if(!isNaN(number)){
			url = './list.do?type=json&page=' + number;
		}else{
			url = './list.do?type=json&page=0';
		}
		fetch(url)
		.then(function(response) {
			return response.json();
		}).then(
				function(articles) {
					var $ul = $('#list-articles');
					articles.forEach(function(art) {
						$ul.append('<li class="list-group-item">' + '<h3>'
								+ art.title + '</h3>' + '<p>' + art.content
								+ '</p>' + '<button class="del-btn" data-id="'
								+ art.id + '">删除</button>' + '</li>');
					})
				}).then(function() {
			$('ul .del-btn').on('click', function() {
				var $self = $(this);
				var id = $self.data('id');
				fetch('./del.do?ajax=true&id=' + id).then(function(response) {
					return response.json();
				}).then(function(res) {
					if (res.ok === 1) {
						$self.parent().slideUp("slow");
					}
				})
			})
		})
	}
	
	$(window).scroll(function() {
		var scrollTop = $(this).scrollTop();
		var scrollHeight = $(document).height();
		var windowHeight = $(this).height();
		if (scrollTop + windowHeight == scrollHeight) {
			i++;
			doGet(i);
		}
	});
})
